package edu.spec.teacher.service.impl;

import edu.spec.basic.dao.iface.IUserDao;
import edu.spec.basic.model.User;
import edu.spec.teacher.dao.iface.IElectDao;
import edu.spec.teacher.dao.iface.IUserElectDao;
import edu.spec.teacher.model.Elect;
import edu.spec.teacher.model.UserElect;
import edu.spec.teacher.service.iface.IElectService;
import org.madgecko.basic.model.Pager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * Author       : MadFrog
 * Date         : 2018/10/6 16:21
 * Description  :
 */
@Service
public class ElectService implements IElectService {

    @Autowired
    private IElectDao electDao;
    @Autowired
    private IUserDao userDao;
    @Autowired
    private IUserElectDao userElectDao;

    @Override
    public void add(Elect e) {
        Elect elect = electDao.add(e);
        String ids = e.getCandidate();
        List<User> voterList = userDao.listUserByIds(ids);
        for (User user : voterList){
            userElectDao.add(new UserElect(user, elect));
        }
    }

    @Override
    public Elect load(Integer id) {
        return electDao.load(id);
    }

    @Override
    public Pager<Elect> find() {
        return electDao.find();
    }

    @Override
    public void update(Elect elect) {
        electDao.update(elect);
    }

    @Override
    public void delete(Integer id) {
        //  删除关联的UserElect
        userElectDao.deleteByElect(id);
        electDao.delete(id);

    }

    private List<Integer> idString2List(String idsString){
        List<Integer> idList = new ArrayList<Integer>();
        String[] idStringArray = idsString.split(",");
        for(String idString : idStringArray){
            idList.add(Integer.parseInt(idString));
        }
        return idList;
    }

}
